package org.zhigong.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.zhigong.entity.Role;
import org.zhigong.entity.Yonghu;
import org.zhigong.service.RoleService;
import org.zhigong.service.YonghuService;

import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2018/4/17 0017.
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private YonghuService yonghuService;
    @Autowired
    private HttpSession session;
    @Autowired
    private RoleService roleService;

    @RequestMapping
    public String index() {
        return "login";
    }

    /**
     * 验证用户名/密码是否正确 验证通过跳转至后台管理首页，验证失败，返回至登录页。
     */
    @RequestMapping("/validate")
    public String validate(Yonghu yonghu, RedirectAttributes attr) {
        if (yonghuService.validate(yonghu)) {
            session.setAttribute("USER_INFO", yonghu);
            attr.addFlashAttribute("userInfo", yonghu);
            Role role = roleService.getRoleById(yonghu.getRoleId());
            session.setAttribute("MENU_INFO", role.getMenuList());
            return "redirect:/main";
        }
        attr.addFlashAttribute("msg", "用户名密码错误，请重新登录");
        return "redirect:/login";
    }

    /**
     * 退出系统
     */
    @RequestMapping("/out")
    public String signOut() {
        session.invalidate();
        return "login";
    }
}
